package com.rtsapp.server.network.protocol;

import java.net.InetSocketAddress;

import com.rtsapp.server.logger.Logger;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import com.rtsapp.server.module.Application;
import com.rtsapp.server.network.protocol.command.AbstractCommandInHandler;
import com.rtsapp.server.network.session.Session;
import com.rtsapp.server.network.session.netty.NettySessionManager;

import io.netty.channel.ChannelHandler.Sharable;


/**
 * 输入处理Handler
 * 使用SessionManager管理接入的连接
 * 
 */
@Sharable
public abstract class ProtocolInHandler extends ChannelInboundHandlerAdapter {

	private static Logger LOGGER =com.rtsapp.server.logger.LoggerFactory.getLogger( ProtocolInHandler.class );

	
	protected NettySessionManager sessionManager;
	
	protected Application application;
	

	public NettySessionManager getSessionManager() {
		return sessionManager;
	}


	public Application getApplication() {
		return application;
	}


	
	
	public boolean initialize( Application application, NettySessionManager sessionManager ){
		
		this.application = application;
		this.sessionManager  = sessionManager;

		return true;
	}


	/**
	 * TCP建立连接成功后, 通道激活
	 * @param ctx
	 * @throws Exception
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {

		Channel channel =  ctx.channel();

		InetSocketAddress address =  (InetSocketAddress)channel.remoteAddress();
		String ip = address.getAddress().getHostAddress();
		int port = address.getPort();

		if( sessionManager.canAccept( ip , port ) ){
			sessionManager.addSession(channel);
		}else{
			ctx.close();
			LOGGER.debug("[session] channel注册失败, sessionManager reject channel: " + ip + ":" + port);
		}

		super.channelActive(ctx);

	}

	/**
	 *
	 * TCP关闭后
	 * @param ctx
	 * @throws Exception
	 */
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {

		Channel channel = ctx.channel();

		InetSocketAddress address =  (InetSocketAddress)channel.remoteAddress();
		String ip = address.getAddress().getHostAddress();
		int port = address.getPort();;

		Session session = sessionManager.getSession( channel );
		if( session != null ){
			sessionManager.removeSession( channel );
		}else{
			LOGGER.error("[session] channel 断开,  channel对应的session为空, 请检查代码, 查找这个bug" + ip + ":" + port);
		}


		super.channelInactive(ctx);
	}

    
}
